#!/bin/sh

PDF_VIEWER=mupdf

SCRIPT_NAME=$(basename $0)
if [ ! -z $1 ]; then
  DOC_NAME=$(basename $1 .tex)
  TEX_FILE=$DOC_NAME.tex
else
  TEX_FILE=$(ls ./*.tex | head -1)
  DOC_NAME=$(basename $1 .tex)
fi
BIB_FILE=$DOC_NAME.bib
PDF_FILE=$DOC_NAME.pdf

checkOptions() {
  if [ -z $TEX_FILE ]; then
    echo "Usage: $SCRIPT_NAME <TeX file>" >&2
    exit 1
  fi
}

initTeXFile() {
  # create tex file
  echo "\documentclass{article}" >>$TEX_FILE
  echo "\usepackage{cite}" >>$TEX_FILE
  echo "\\\begin{document}" >>$TEX_FILE
  echo "\\\title{hy\\TeX}" >>$TEX_FILE
  echo "\\maketitle" >>$TEX_FILE
  echo "" >>$TEX_FILE
  echo "Welcome using hy\\TeX~\\\cite{hyTeX}!" >>$TEX_FILE
  echo "" >>$TEX_FILE
  echo "\\\bibliographystyle{plain}" >>$TEX_FILE
  echo "\\\bibliography{$DOC_NAME}" >>$TEX_FILE
  echo "\\end{document}" >>$TEX_FILE

  # create bib file
  echo "@misc{hyTeX, howpublished=\"haoyutan@gmail.com\", }" >>$BIB_FILE

  # compile
  compileTeXFile
}

compileTeXFile() {
  latexmk -pdfps $TEX_FILE >/dev/null
}

main() {
  checkOptions
  if [ ! -f $TEX_FILE ]; then
    initTeXFile
  else
    compileTeXFile
  fi

  $PDF_VIEWER $PDF_FILE >/dev/null 2>&1 &

  MOD_TIME=$(stat -c %Y $TEX_FILE)
  ERR_NUM=0
  while true; do
    sleep 0.2
    MOD_TIME2=$(stat -c %Y $TEX_FILE)
    if [ $MOD_TIME -ne $MOD_TIME2 ]; then
      compileTeXFile
      CUR_WID=$(xdotool getactivewindow)
      xdotool windowactivate $VIEWER_WID && xdotool key r
      xdotool windowactivate $CUR_WID
      MOD_TIME=$MOD_TIME2
    fi

    VIEWER_WID=$(xdotool search --title $DOC_NAME.dvi)
    if [ -z $VIEWER_WID ]; then
      ERR_NUM=$(($ERR_NUM + 1))
      if [ $ERR_NUM -gt 10 ]; then
        echo "Viewer closed, exit."
        exit 0
      fi
    else
      ERR_NUM=0
    fi
  done
}

main >$DOC_NAME.hyTeX.log 2>&1 &
